/*
 * @Description: 
 * @FilePath: /STM32/USER/api/rs485.c
 * @Author: Wei Zhou
 * @Github: https://github.com/zromyk
 * @Date: 2021-04-28 15:25:19
 * @LastEditors: Wei Zhou
 * @LastEditTime: 2021-04-28 15:25:19
 * @Copyright: Copyright  2017 muyiro. All rights reserved.
 */
 
#include "usart.h"
#include "gpio.h"
#include "RS485.h"

void rs485_init(rs485_dev *rs485, USART_Dev *usart, PIN_Dev pin_re)
{
    rs485->usart = usart;
    rs485->pin_re = pin_re;

    gpio_out_init(rs485->pin_re, GPIO_PuPd_UP, 0);
    rs485_rx_mode(rs485);
}

void rs485_write_byte(rs485_dev *rs485, const uint8_t byte)
{
    rs485_tx_mode(rs485);
    USART_SendData(rs485->usart->USARTx, (uint8_t)byte);
    while (USART_GetFlagStatus(rs485->usart->USARTx, USART_FLAG_TC) == RESET)
        ;
    rs485_rx_mode(rs485);
}

void rs485_write_buffer(rs485_dev *rs485, const uint8_t *buf, uint32_t length)
{
    uint32_t i;

    rs485_tx_mode(rs485);
    for (i = 0; i < length; ++i)
    {
        USART_SendData(rs485->usart->USARTx, (uint8_t)*buf);
        while (USART_GetFlagStatus(rs485->usart->USARTx, USART_FLAG_TXE) == RESET)
            ;
        buf++;
    }
    while (USART_GetFlagStatus(rs485->usart->USARTx, USART_FLAG_TC) == RESET)
        ;
    rs485_rx_mode(rs485);
}

void rs485_write_string(rs485_dev *rs485, const uint8_t *str)
{
    rs485_tx_mode(rs485);
    while ((*str) != '\0')
    {
        USART_SendData(rs485->usart->USARTx, (uint8_t)*str);
        while (USART_GetFlagStatus(rs485->usart->USARTx, USART_FLAG_TXE) == RESET)
            ;
        str++;
    }
    while (USART_GetFlagStatus(rs485->usart->USARTx, USART_FLAG_TC) == RESET)
        ;
    rs485_rx_mode(rs485);
}

